package calao.csp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

public class ScriptInterpreter 
{
	
	HashMap<String,ScriptCommand> commandMap = new HashMap<String,ScriptCommand>();
		
	public void eval(InputStream input, OutputStream output)
	throws IOException
	{
		int b0;
		start: while ((b0=input.read())!=-1) {
			if (b0=='<') {
				int b1 = input.read();
				if (b1=='?') {
					StringBuffer buffer = new StringBuffer();
					while ((b0=input.read())!=-1) {
						if (b0=='?') {
							b1 = input.read();
							if (b1=='>') {
								eval(buffer.toString(), output);
								continue start;
							}
							else {
								buffer.append((char)b0);
								buffer.append((char)b1);
							}
						}
						else buffer.append((char)b0);
					}
				}
				else {
					output.write(b0);
					output.write(b1);
				}
			}
			else output.write(b0);
		}
	}
	
	public void eval(String commandLine, OutputStream output)
	throws IOException
	{
		CommandParser parser = new CommandParser(commandLine);
		parser.parse();
		ScriptCommand command = commandMap.get(parser.getCommandName());
		if (command!=null) {
			command.execute(parser.getCommandArguments(), output);
		}
	}
	
	public void register(String name, ScriptCommand command)
	{
		commandMap.put(name, command);
	}
	
}
